<template>
  <div>
    <!-- <div class="handle">
      <el-button v-if="isLook" @click="isLook = !isLook">编辑</el-button>
      <el-button v-else @click="save">保存</el-button>
    </div> -->
    <div class="slot"></div>
    <div :class="['markdown-box', { 'markdown-box-look': (fileContent && isLook) || is_public }]">
      <i v-if="isLook && fileContent" @click="isLook = !isLook" class="el-icon-edit to-edit"></i>
      <!-- <el-button v-if="isLook && fileContent" @click="isLook = !isLook" size="mini" class="to-edit">编辑</el-button> -->
      <el-button v-if="!isLook" @click="save" size="mini" class="none-type save-btn">保存</el-button>
      <a href="javascript:;" class="edit-btn" v-if="!fileContent && isLook && !is_public"
        @click="isLook = !isLook">编辑README</a>
      <markdown-editor-look :value="fileContent" v-show="isLook && fileContent" />
      <markdown-editor @val="val" :value="fileContent" v-show="!isLook" />
    </div>
  </div>
</template>

<script>
import { previewFile, uploadFile } from "@/api/file"
import MarkdownEditor from "../MarkdownEditor";
import MarkdownEditorLook from "../MarkdownEditor/look.vue";
import { Base64 } from "js-base64";
// import { domain } from "@/config";
export default {
  name: "FilePreview",
  props: ['biz_id', 'relative_path', 'type', 'is_public'],
  data() {
    return {
      myInfo: {},
      fileContent: '',
      isLook: true
    }
  },
  components: {
    MarkdownEditor,
    MarkdownEditorLook
  },
  watch: {
    isLook(val) {
      this.$emit('editState', val)
    }
  },
  methods: {
    async preview() {
      let encodedRelativePath = encodeURIComponent(Base64.encode('/README.md'))

      let [err, res] = await this.$awaitWrap(previewFile({
        bizId: this.biz_id,
        encodedRelativePath,
        type: this.type,
        userId: this.is_public ? 'public' : this.myInfo.id,
        ignore: true
      }))
      console.log(err)
      console.log(res)
      this.fileContent = res
    },
    dataURLtoFile(dataurl, filename) {
      //将base64转换为文件
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    async save() {
      let data = new FormData()
      let filesFile = this.dataURLtoFile(
        `data:text/markdown;base64,${Base64.encode(this.fileContent)}`,
        this.fileName
      )
      data.append("chunkNumber", 1)
      data.append("totalChunks", 1)
      data.append("repeType", '')
      data.append("filename", filesFile.name)
      data.append("relativePath", '/README.md')
      data.append("userId", this.myInfo.id)
      data.append("type", this.type)
      data.append("bizId", this.biz_id)
      data.append("file", new Blob([filesFile]), filesFile.name)

      await uploadFile(data)
      this.isLook = !this.isLook
    },
    val(content) {
      this.fileContent = content
    }
  },
  async mounted() {
    this.myInfo = await this.$myInfo(this)
    this.preview()
    // this.fileContent = '# 蔚时\n\n## 需要安装的环境\n```\nnodejs v16版本以上\n```\n\n## 安装依赖\n```\nnpm install\n```\n\n## 启动命令\n```\nnpm run dev\n\n```\n\n### 访问方式\n```\nhttp://localhost:8080/#/\n\n```\n\n### 路由配置说明\n```\naffiliation             ====> 关联的类型（main：第一层级）\nmeta                    ====> 路由详情（名字、icon等）\nhideDetails             ====> 是否隐藏详情\n\n```\n### 路由列表\n```\n/notebook/lis               ====> 模型开发\n/task/lis                   ====> 模型训练 \n/dataset/lis                ====> 数据集列表\n/image/lis                  ====> 镜像列表\n/user/login                 ====> 登录\n\n```\n\n### 配置文件 (src/config.js)\n```\nconfigExpires                           ====> cookies 过期时间\ndomain（FN sHost）                      ====> 设置API host\nWAY                                     ====> 部署方式（公开、私有）\nisLoginSkip（FN loginSkipLis）          ====> 不跳转登录的路由\n\n```\n\n'
  }
}
</script>

<style lang="less" scoped>
.slot {
  width: 100%;
  // height: 6px;
  background: #FFF;
}

.markdown-box {
  // min-height: 200px;
  background: #FFF;
  // border: 1px solid #DCDFE6;
  position: relative;
  // background: #F6F8FA;
  background: rgba(#808080, .1);

  // box-shadow: rgba(0, 0, 0, .1) 0px 2px 12px 0px;
  .edit-btn {
    line-height: 160px;
    text-align: center;
    display: block;
    color: #0077FF;
    font-size: 16px;
  }

  .to-edit {
    position: absolute;
    right: 20px;
    top: 10px;
    font-size: 20px;
    cursor: pointer;
    z-index: 1502;
  }

  .save-btn {
    position: absolute;
    right: 136px;
    top: 8px;
    z-index: 1502;
  }
}

.markdown-box-look {
  border: 0;
  background: rgba(0, 0, 0, 0);
}

.handle {
  text-align: right;
  padding-bottom: 20px;
}
</style>